<template>
  <div id="app">
    <el-container>
      <el-header
        style="
          background-color: #687581;
          height: 60px;
          color: #fff;
          font-size: 30px;
        "
      >
        <span>华南农业大学共享电动车与自行车管理系统</span>
        <span style="font-size: 20px; position: relative; float: right"
          >{{ username }}
          <span><el-button @click="logout">Logout</el-button></span>
        </span>
      </el-header>

      <el-container>
        <el-aside width="200px">
          <el-menu
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b"
          >
            <el-submenu index="1" :disabled="disabled">
              <template slot="title">
                <i class="el-icon-setting"></i>
                <span slot="title">
                  <span>车辆管理</span>
                </span>
              </template>
              <el-menu-item-group>
                <el-menu-item index="1-1" @click="toInfo"
                  ><i class="el-icon-more"></i> 车辆信息</el-menu-item
                >
                <el-menu-item index="1-2" @click="addElec"
                  ><i class="el-icon-plus"></i>添加电动车</el-menu-item
                >
                <el-menu-item index="1-3" @click="addBike"
                  ><i class="el-icon-plus"></i>添加自行车</el-menu-item
                >

                <el-menu-item index="1-4" @click="addRepair"
                  ><i class="el-icon-unlock"></i>添加维修点</el-menu-item
                >
              </el-menu-item-group>
            </el-submenu>

            <el-menu-item index="2" :disabled="disabled">
              <i class="el-icon-s-data"></i>
              <span slot="title" @click="toStatistic"> 车辆统计 </span>
            </el-menu-item>

            <el-submenu index="3" :disabled="disabled">
              <template slot="title">
                <i class="el-icon-location"></i>
                <span>充电桩管理</span>
              </template>
              <el-menu-item-group>
                <el-menu-item index="3-1" @click="toCgpItemsInfo"
                  >充电桩信息</el-menu-item
                >
                <el-menu-item index="3-2" @click="addChargingPile"
                  >标记充电桩</el-menu-item
                >
              </el-menu-item-group>
            </el-submenu>

            <el-submenu index="4" :disabled="disabled">
              <template slot="title">
                <i class="el-icon-location"></i>
                <span>停车点管理</span>
              </template>
              <el-menu-item-group>
                <el-menu-item index="4-1" @click="addParkingSpace"
                  >标记停车点</el-menu-item
                >
              </el-menu-item-group>
            </el-submenu>

            <!-- <el-menu-item index="5">
              <i class="el-icon-monitor"></i>
              <span slot="title">车辆数量管理</span>
            </el-menu-item> -->
          </el-menu>
        </el-aside>
        <el-main>
          <div
            class="header1"
            style="
              height: 50px;
              background-color: rgb(196, 227, 228);
              z-index: 9999;
              margin-top: -10px;
            "
          >
            <div>
              <el-menu
                :default-active="activeIndex"
                class="el-menu-demo"
                mode="horizontal"
                @select="handleSelect"
                background-color="#687581"
                text-color="#fff"
                active-text-color="rgb(255, 208, 75)"
              >
                <el-submenu index="1" :disabled="disabled">
                  <template slot="title">专题地图</template>
                  <el-menu-item index="1-1" @click="drawer"
                    >各校区电动车数量</el-menu-item
                  >
                </el-submenu>

                <el-submenu index="2" :disabled="disabled">
                  <template slot="title">辅助分析图</template>
                  <el-menu-item
                    index="2-1"
                    @click="
                      showHeatMap()
                      showHeatMapFlag = true
                    "
                    >电动车分布热力图
                  </el-menu-item>

                  <el-menu-item
                    v-show="showHeatMapFlag"
                    index="2-2"
                    @click="
                      hideHeatMap()
                      showHeatMapFlag = false
                    "
                    >关闭热力度
                  </el-menu-item>
                  <!-- <el-menu-item index="2-3" @click="drawDestination"
                    >最短路径分析</el-menu-item
                  > -->
                </el-submenu>
              </el-menu>
            </div>

            <div
              style="
                position: relative;
                top: -55px;
                right: -475px;
                width: 330px;
              "
            >
              <input
                style="
                  width: 210px;
                  height: 30px;
                  position: relative;
                  left: 485px;
                  top: -55px;
                "
                id="tipinput"
                type="text"
                placeholder="请输入关键字"
              />
            </div>
          </div>

          <div>
            <div id="container1">
              <div
                id="map"
                style="position: relative; margin: 420px 10px; height: 700px"
              >
                <!-- 图例 -->
                <div
                  style="
                    position: absolute;
                    top: 35px;
                    left: 3px;
                    z-index: 2000;
                    background-color: rgba(0, 0, 0, 0.1);
                    padding-right: 10px;
                    width: 100px;
                  "
                >
                  <ul class="color-list">
                    <li style="font-size: 14px; line-height: 30px">
                      停车点:
                      <span
                        style="
                          display: inline-block;
                          width: 30px;
                          height: 15px;
                          background-color: #aab86d;
                        "
                      ></span>
                    </li>
                    <li style="font-size: 14px; line-height: 30px">
                      充电桩:
                      <span
                        style="
                          display: inline-block;
                          width: 30px;
                          height: 15px;
                          background-color: green;
                        "
                      ></span>
                    </li>
                    <li style="font-size: 14px; line-height: 30px">
                      共享单车:
                      <span
                        ><img
                          src="img/bicycle.png"
                          alt=""
                          style="width: 25px; height: 25px"
                      /></span>
                    </li>
                    <li style="font-size: 14px; line-height: 30px">
                      共享电动车:<span
                        ><img
                          src="img/scooter.png"
                          alt=""
                          style="width: 25px; height: 25px"
                      /></span>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
            <div
              id="heatMapBox"
              v-show="showHeatMapFlag"
              style="
                width: 589px;
                height: 600px;
                position: relative;
                float: right;
                top: -590px;
              "
            ></div>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 添加电动车信息 -->
    <el-dialog
      title="请输入车辆信息"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose1"
    >
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="车辆编号" prop="no">
          <el-input v-model="form.no" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="使用状态">
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="车牌颜色" prop="color" v-show="flag1">
          <el-input v-model="form.color" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="车辆电量" prop="battery" v-show="flag1">
          <el-input v-model="form.battery" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
          <el-button @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 显示车辆信息 -->
    <showInfo
      :id="form.id"
      :no="form.no"
      :state="form.state"
      :color="form.color"
      :cumlative_usage_time="form.cumlative_usage_time"
      :monthly_usage_times="form.monthly_usage_times"
      :battery="form.battery"
    ></showInfo>

    <cgpInfo
      :id="cgpId"
      :cgpArea="cgpArea"
      :cgpState="cgpState"
      :cgpNum="cgpNumm"
      ref="cgp"
    ></cgpInfo>

    <poiInfo
      :address="poiInfoForm.address"
      :name="poiInfoForm.name"
      :type="poiInfoForm.type"
      :tel="poiInfoForm.tel"
      :photos="poiInfoForm.photos"
      :photosFlag="photosFlag"
    ></poiInfo>

    <drawer></drawer>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import * as turf from '@turf/turf'
import pubsub from 'pubsub-js'

import showInfo from '../components/showInfo.vue'
import cgpInfo from '../components/ChargingPileInfo.vue'
import poiInfo from '../components/poiInfo.vue'
import drawer from '../components/drawer.vue'
import poiData from '../../public/js/scauPoi'

import { mapMutations, mapState } from 'vuex'
import { nanoid } from 'nanoid'

export default {
  name: 'app',
  data() {
    var validateNo = (rule, value, callback) => {
      const reg = /^HN.\d{6}$/

      if (value === '') {
        callback(new Error('请输入编号'))
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确编号，格式:'HN.xxxxxx',如:'HN000001'"))
      } else {
        if (this.form.checkPass !== '') {
          this.$refs.form.validateField('checkPass')
        }
        callback()
      }
    }

    const validateColor = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入车牌颜色'))
      } else {
        // this.$refs.form.validateField()
        callback()
      }
    }

    const validateBattery = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入车辆电量'))
      } else {
        callback()
      }
    }

    return {
      disabled: false,
      username: '',
      cgpId: '',
      cgpPosition: [],
      cgpArea: '',
      cgpState: '',
      cgpNumm: '',
      photosFlag: true,
      heatMapBoxB: null,
      showHeatMapFlag: false,
      auto: null,
      placeSearch: null,
      heatMap: null,
      heatMapDataList: [],
      polyLineGeoJson: '',
      polylineRecord: [],
      ifShowPath: true,
      marker: '',
      p: '',
      AMap: '',
      geojson: '',
      flag1: false,
      pType: '',
      options: [
        {
          value: '正常使用',
          label: '正常使用',
        },
        {
          value: '维修中',
          label: '维修中',
        },
      ],
      value: '',
      input: '',
      mouseTool: '',
      arr: [],
      map: '',
      activeIndex: '1',
      activeIndex2: '1',
      dialogVisible: false,
      dialogVisible2: false,
      // dialogVisible3: false,
      lng: '',
      lat: '',
      originLng: '',
      originLat: '',
      // path: [],

      //电动车信息

      form: {
        id: '',
        no: '',
        state: '',
        color: '',
        battery: '',
        cumlative_usage_time: '',
        monthly_usage_times: '',
        trial: '',
        isUsable: '',

        pass: '',
        checkPass: '',
      },

      poiInfoForm: {
        name: '',
        address: '',
        type: '',
        tel: '',
        photos: '',
      },

      rules: '',

      rules1: {
        no: [{ validator: validateNo, trigger: 'blur' }],
        color: [{ validator: validateColor, trigger: 'blur' }],
        battery: [{ validator: validateBattery, trigger: 'blur' }],
      },

      rules2: {
        no: [{ validator: validateNo, trigger: 'blur' }],
      },
    }
  },

  mounted() {
    // console.log("114514");
    this.initmap()

    this.$nextTick(() => {
      this.username = localStorage.getItem('username')
      if (this.$store.state.power == '普通用户') {
        this.disabled = true
      } else {
        this.disabled = false
      }
    })
  },

  computed: {
    ...mapState([
      'dialogVisible3',
      'showPathT',
      'showBufferT',
      'showDestinationT',
    ]),

    showPath() {
      return this.$store.state.showPathT
    },

    showBuffer() {
      return this.$store.state.showBufferT
    },

    showDestination() {
      return this.$store.state.showDestinationT
    },
  },

  watch: {
    value(newVal, old) {
      this.form.state = newVal
    },

    showPath() {
      if (this.showPathT) {
        this.drawPath()
      }
    },

    showBuffer() {
      if (this.showBufferT) {
        this.draweBuffer()
      }
    },

    showDestination() {
      if (this.showDestinationT) {
        this.drawDestination()
      }
    },
  },

  components: {
    showInfo,
    drawer,
    cgpInfo,
    poiInfo,
  },

  methods: {
    ...mapMutations([
      'edittrue',
      'edittrue2',
      'edittrue3',
      'drawerTrue',
      'editfalse2',
      'showDestinationFalse',
    ]),

    logout() {
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      this.$router.push('/')
      window.location.reload()
    },

    ringTool() {
      const ruler1 = new AMap.RangingTool(this.map)
      ruler1.turnOn()
    },

    drawer() {
      this.drawerTrue()
    },

    //绘制缓冲
    draweBuffer() {
      // console.log(this.$refs.cgp.input);

      let geojson = new AMap.GeoJSON({
        geoJSON: null,
      })

      this.cgpPosition.push([this.cgpPosition[0][0], this.cgpPosition[0][1]])

      let path2 = []
      let path3 = ''
      const reg = /^(?:100|\d{1,2})$/
      if (this.$refs.cgp.input) {
        if (!reg.test(this.$refs.cgp.input)) {
          return this.$message.error('缓冲距离超出范围，请重新输入')
        }

        var polygon = turf.polygon([this.cgpPosition], { name: 'poly1' })
        var buffered = turf.buffer(polygon, this.$refs.cgp.input / 1000, {})
        const area = turf.area(buffered)
        for (
          let index = 0;
          index < buffered.geometry.coordinates.length;
          index++
        ) {
          let info = buffered.geometry.coordinates[index]

          for (let index2 = 0; index2 < info.length; index2++) {
            path2.push(new AMap.LngLat(info[index2][0], info[index2][1]))
            path3 += info[index2][0] + ' ' + info[index2][1] + ';'
          }
        }
        var polygon2 = new AMap.Polygon({
          path: path2,
          fillColor: '#fff', // 多边形填充颜色
          borderWeight: 2, // 线条宽度，默认为 1
          strokeColor: 'red', // 线条颜色
        })

        this.map.add(polygon2)

        geojson.addOverlay(polygon2)
        this.getNumByBuffer(path3, area)
        // this.editfalse2();

        geojson.eachOverlay((item) => {
          item.on('dblclick', (e) => {
            this.$confirm('删除缓冲区?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                })
                this.map.remove(polygon2)
              })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除',
                })
              })
          })
        })
      }
    },

    getNumByBuffer(buffer, area) {
      this.$axios({
        method: 'get',
        url: `/getNumByBuffer?buffer=${buffer}`,
      }).then((res) => {
        const data = { num: res.data, area: Math.floor(area) }
        pubsub.publish('getNum', data)
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          this.$message({
            message: '添加成功',
            type: 'success',
          })

          if (this.pType === 'ebike') {
            this.writeEBike()
          } else if (this.pType === 'bike') {
            this.writeBike()
          }
          this.dialogVisible = false
        } else {
          // console.log("error submit!!");
          this.$message.error('信息有误')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleSelect(key, keyPath) {
      // console.log(key, keyPath);
    },

    handleClose1(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },

    handleClose2(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },

    //获取所有共享单车
    getAllSharedBike(geojson) {
      this.$axios({
        method: 'get',
        url: '/getAllSharedBike',
      })
        .then((res) => {
          // console.log(res.data);

          // if(res.data = "null"){

          // }else{

          // }

          for (let index = 0; index < res.data.length; index++) {
            // console.log(res.data[index]);
            const info = res.data[index]

            var startIcon = new AMap.Icon({
              // 图标尺寸
              size: new AMap.Size(50, 50),
              // 图标的取图地址
              image: 'img/bicycle.png',
              // 图标所用图片大小
              imageSize: new AMap.Size(25, 25),
              // 图标取图偏移量
              imageOffset: new AMap.Pixel(0, 0),
            })

            let marker = new AMap.Marker({
              offset: new AMap.Pixel(-5, -5),
              position: new AMap.LngLat(
                res.data[index].lng,
                res.data[index].lat
              ),
              icon: startIcon,
              type: 'bike',

              //物体标识
              bikeId: info._id,
              id: info.sbId,
              no: info.no,
              state: info.state,
              monthly_usage_times: info.monthlyUsageTimes,
            })

            this.map.add(marker)
            geojson.addOverlay(marker)
          }

          geojson.eachOverlay((item) => {
            item.on('click', (e) => {
              console.log(e.target._opts)

              this.form.no = ''
              this.form.state = ''
              this.form.color = ''
              this.form.battery = ''
              this.form.cumlative_usage_time = ''
              this.form.monthly_usage_times = ''

              this.form.id = e.target._opts.id
              this.form.no = e.target._opts.no
              this.form.state = e.target._opts.state
              this.form.monthly_usage_times = e.target._opts.monthlyUsageTimes
            })
          })
        })
        .catch((error) => {
          console.log(error)
        })
    },

    //获取所有共享电动车
    getAllSharedEbike(geojson) {
      this.$axios({
        method: 'get',
        url: '/getAllSharedEBike',
      }).then((res) => {
        for (let index = 0; index < res.data.length; index++) {
          let pathAr = []
          const info = res.data[index]
          this.heatMapDataList.push({
            lng: info.lng,
            lat: info.lat,
            count: 80,
          })

          let trail = info.trail
          if (trail) {
            const p = trail.split(';')

            for (let index = 0; index < p.length; index++) {
              pathAr.push(
                new AMap.LngLat(p[index].split(',')[0], p[index].split(',')[1])
              )
            }
          }

          var startIcon = new AMap.Icon({
            size: new AMap.Size(50, 50),
            image: 'img/scooter.png',
            imageSize: new AMap.Size(25, 25),
            imageOffset: new AMap.Pixel(0, 0),
          })

          let marker = new AMap.Marker({
            offset: new AMap.Pixel(-5, -5),
            position: new AMap.LngLat(info.lng, info.lat),
            icon: startIcon,
            type: 'ebike',

            //物体标识
            ebikeId: info._id,
            id: info.sebId,
            no: info.no,
            color: info.color,
            battery: info.battery,
            state: info.state,
            cumlative_usage_time: info.cumlativeUsageTime,
            monthly_usage_times: info.monthlyUsageTimes,
            trial: pathAr,
          })

          this.map.add(marker)
          geojson.addOverlay(marker)
        }

        geojson.eachOverlay((item) => {
          item.on('click', (e) => {
            this.edittrue()
            this.originLng = e.target._opts.position.lng
            this.originLat = e.target._opts.position.lat
            this.marker = item
            this.form.id = e.target._opts.id
            this.form.no = e.target._opts.no
            this.form.state = e.target._opts.state
            this.form.color = e.target._opts.color
            this.form.battery = e.target._opts.battery
            this.form.cumlative_usage_time = e.target._opts.cumlative_usage_time
            this.form.monthly_usage_times = e.target._opts.monthly_usage_times
            this.form.trial = e.target._opts.trial
          })
        })
      })
    },

    moving(path) {
      this.marker.moveAlong(path, {
        // 每一段的时长
        duration: 100, //可根据实际采集时间间隔设置
        // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
        autoRotation: true,
      })
    },

    //获取停车点
    getParkingLots() {
      let arr = []

      let geojson = new AMap.GeoJSON({
        geoJSON: null,
      })

      this.$axios({
        method: 'get',
        url: '/getAllStop',
      }).then((res) => {
        if (res.data.code == 403) {
          return
        } else {
          let pathArr = []

          for (let index = 0; index < res.data.length; index++) {
            // res.data[index].locality.split(";");

            let arr1 = []

            for (
              let index2 = 0;
              index2 < res.data[index].locality.split(';').length;
              index2++
            ) {
              // console.log(res.data[index].locality.split(";")[index2].split(" "));

              if (
                res.data[index].locality.split(';')[index2].split(' ')[0] &&
                res.data[index].locality.split(';')[index2].split(' ')[1]
              ) {
                arr1.push(
                  new AMap.LngLat(
                    res.data[index].locality.split(';')[index2].split(' ')[0],
                    res.data[index].locality.split(';')[index2].split(' ')[1]
                  )
                )
              }
            }

            pathArr.push(arr1)
          }

          for (let index = 0; index < pathArr.length; index++) {
            // 创建折线实例
            var polygon = new AMap.Polygon({
              path: pathArr[index],
              strokeWeight: 0.1,
              fillColor: '#aab86d',
              fillOpacity: 0.7,

              strokeStyle: 'solid',
              type: 'parkingLot',

              //物体标识
              polygonId: res.data[index].sid,
            })

            // 将折线添加至地图实例
            this.map.add(polygon)
            geojson.addOverlay(polygon)
          }

          //覆盖物点击事件
          geojson.eachOverlay((item) => {
            item.on('dblclick', (e) => {
              this.$confirm('删除停车点, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              })
                .then(() => {
                  this.$axios({
                    method: 'get',
                    url: `/deleteStop?sId=${e.target._opts.polygonId}`,
                  }).then((res) => {
                    this.$message({
                      type: 'success',
                      message: '删除成功!',
                    })

                    // this.map.remove(polygon)

                    window.location.reload()
                  })
                })
                .catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消删除',
                  })
                })
            })
          })
        }
      })
    },

    //获取充电桩区域
    getChargingPiles() {
      let geojson = new AMap.GeoJSON({
        geoJSON: null,
      })
      let arr = []

      this.$axios({
        method: 'get',
        url: '/getAllChargingPile',
      }).then((res) => {
        let pathArr = []

        for (let index = 0; index < res.data.length; index++) {
          // res.data[index].locality.split(";");

          let arr1 = []

          for (
            let index2 = 0;
            index2 < res.data[index].locality.split(';').length;
            index2++
          ) {
            if (
              res.data[index].locality.split(';')[index2].split(' ')[0] &&
              res.data[index].locality.split(';')[index2].split(' ')[1]
            ) {
              arr1.push(
                new AMap.LngLat(
                  res.data[index].locality.split(';')[index2].split(' ')[0],
                  res.data[index].locality.split(';')[index2].split(' ')[1]
                )
              )
            }
          }

          pathArr.push(arr1)
        }

        for (let index = 0; index < pathArr.length; index++) {
          var polygon = new AMap.Polygon({
            path: pathArr[index],
            strokeWeight: 0.1,
            fillColor: 'green',
            fillOpacity: 0.4,
            chargingPileId: res.data[index].cpId,
            cgpState: res.data[index].state,
            num: res.data[index].num,
          })

          // 将折线添加至地图实例
          this.map.add(polygon)
          geojson.addOverlay(polygon)
        }

        //覆盖物点击事件
        geojson.eachOverlay((item) => {
          item.on('dblclick', (e) => {
            this.cgpState = e.target._opts.cgpState
            this.cgpId = e.target._opts.chargingPileId
            this.cgpNumm = e.target._opts.num
            this.edittrue2()

            this.cgpPosition = []
            e.target._opts.path.forEach((e) => {
              this.cgpPosition.push([e[0], e[1]])
            })
            var area = AMap.GeometryUtil.ringArea(this.cgpPosition)
            this.cgpArea = Math.floor(area)
          })
        })
      })
    },

    getRepairPoints() {
      let geojson = new AMap.GeoJSON({
        geoJSON: null,
      })

      this.$axios({
        method: 'get',
        url: '/repairPoint/getAll',
      }).then((res) => {
        for (let index = 0; index < res.data.length; index++) {
          const info = res.data[index]
          var startIcon = new AMap.Icon({
            // 图标尺寸
            size: new AMap.Size(50, 50),
            // 图标的取图地址
            image: 'img/repair.jpg',
            // 图标所用图片大小
            imageSize: new AMap.Size(15, 15),
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(0, 0),
          })

          let marker = new AMap.Marker({
            offset: new AMap.Pixel(-5, -5),
            position: new AMap.LngLat(res.data[index].lng, res.data[index].lat),
            icon: startIcon,
            type: 'repairPoint',

            //物体标识
            repairPointId: info.rpId,
          })

          this.map.add(marker)
          geojson.addOverlay(marker)
        }

        geojson.eachOverlay((item) => {
          item.on('click', (e) => {
            this.$confirm('确认删除维修点?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                this.$axios({
                  method: 'post',
                  url: `/repairPoint/delete?rpId=${e.target._opts.repairPointId}`,
                }).then((res) => {
                  this.$message({
                    type: 'success',
                    message: '删除成功!',
                  })

                  setTimeout(() => {
                    window.location.reload()
                  }, 500)
                })
              })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除',
                })
              })
          })
        })
      })
    },

    //添加车辆
    addBike() {
      this.drawBike(this.mouseTool)
    },

    writeBike() {
      //参数
      const params = {
        no: this.form.no,
        state: this.form.state,
        // cumlative_usage_time: "2h",
        monthly_usage_times: '10',
        // trail: "A->B->C->D->E",

        // battery: this.battery,
        lng: this.lng,
        lat: this.lat,
      }
      //添加共享单车
      this.$axios({
        method: 'post',
        url: `addSharedBike?no=${params.no}&state=${params.state}&monthlyUsageTimes=${params.monthly_usage_times}&lng=${params.lng}&lat=${params.lat}`,
        data: params,
      }).then((res) => {
        console.log(res)
      })
    },

    //添加电动车
    addElec() {
      this.drawEbike(this.mouseTool)
    },

    writeEBike() {
      //参数
      const params = {
        no: this.form.no,
        state: this.form.state,
        cumlative_usage_time: '53h',
        monthly_usage_times: '53',
        trial: '',
        color: this.form.color,
        battery: this.form.battery,
        lng: this.lng,
        lat: this.lat,
      }

      //添加共享电动车
      this.$axios({
        method: 'post',
        url: `/addSharedEBike?no=${params.no}&state=${params.state}&cumlativeUsageTime=${params.cumlative_usage_time}&monthlyUsageTimes=${params.monthly_usage_times}&trail=${params.trial}&color=${params.color}&battery=${params.battery}&lng=${params.lng}&lat=${params.lat}`,
        data: params,
      }).then((res) => {
        console.log(res)
      })
    },

    //添加充电桩
    addChargingPile() {
      const fillcolor = 'green'
      const type = 'chargingPile'
      this.drawPolygon(this.mouseTool, fillcolor, type)
    },

    //添加维修点
    addRepair() {
      this.drawRepairPoint(this.mouseTool)
    },

    writeRepairPoint() {},

    toInfo() {
      let { href } = this.$router.resolve({
        path: '/iteminfo',
        // query: { info: "asd" },
      })
      window.open(href, '_blank')
    },

    toStatistic() {
      let { href } = this.$router.resolve({
        path: '/statistic',
      })

      window.open(href, '_blank')
    },

    toMap() {
      let { href } = this.$router.resolve({
        path: '/mymap',
      })

      window.open(href, '_blank')
    },

    toCgpItemsInfo() {
      let { href } = this.$router.resolve({
        path: '/cgpItems',
      })

      window.open(href, '_blank')
    },

    getpoint() {
      axios.get().then((res) => {})
    },

    drawBike(mouseTool) {
      var startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(50, 50),
        // 图标的取图地址
        image: 'img/bicycle.png',
        // 图标所用图片大小
        imageSize: new AMap.Size(25, 25),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(0, 0),
      })
      mouseTool.marker({
        offset: new AMap.Pixel(-5, -5),
        icon: startIcon,
        type: 'bike',
      })
    },

    drawEbike(mouseTool) {
      var startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(50, 50),
        // 图标的取图地址
        image: 'img/scooter.png',
        // 图标所用图片大小
        imageSize: new AMap.Size(25, 25),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(0, 0),
      })
      mouseTool.marker({
        offset: new AMap.Pixel(-5, -5),
        icon: startIcon,
        type: 'ebike',
      })
    },

    drawRepairPoint(mouseTool) {
      var startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(50, 50),
        // 图标的取图地址
        image: 'img/repair.jpg',
        // 图标所用图片大小
        imageSize: new AMap.Size(15, 15),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(0, 0),
      })
      mouseTool.marker({
        offset: new AMap.Pixel(-5, -5),
        icon: startIcon,
        type: 'repairPoint',
      })
    },

    //路径规划目标点
    drawDestination() {
      var startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(70, 70),
        // 图标的取图地址
        image: 'img/destination.png',
        // 图标所用图片大小
        imageSize: new AMap.Size(50, 50),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(0, 0),
      })
      this.mouseTool.marker({
        offset: new AMap.Pixel(-23, -35),
        icon: startIcon,
        type: 'destination',
      })

      // console.log(this.originLng, this.originLat);
    },

    drawPath() {
      let polyLineGeoJson2 = new AMap.GeoJSON({
        geoJSON: null,
      })

      if (this.form.trial) {
        let pathArr = []
        var polyline = new AMap.Polyline({
          no: this.form.no,
          // map: this.map,
          path: this.form.trial,
          borderWeight: 2, // 线条宽度，默认为 1
          showDir: true,
          strokeColor: '#28F', //线颜色
          strokeWeight: 6, //线宽
          lineJoin: 'round', // 折线拐点连接处样式
        })

        console.log()

        for (
          let index = 0;
          index < polyLineGeoJson2._overlays.length;
          index++
        ) {
          this.polylineRecord.add(polyLineGeoJson2._overlays[index]._opts.no)
        }

        if (!this.polylineRecord.has(this.form.no)) {
          this.map.add(polyline)

          polyLineGeoJson2.addOverlay(polyline)
        }

        polyLineGeoJson2.eachOverlay((item) => {
          item.on('click', (e) => {
            this.moving(e.target._opts.path)
          })

          item.on('rightclick', (e) => {
            this.map.remove(polyline)
          })
        })
      }
    },

    drawPolygon(mouseTool, fillColor, type) {
      mouseTool.polygon({
        // strokeColor: "#FF33FF",
        // strokeOpacity: 1,
        strokeWeight: 0.1,
        // strokeOpacity: 0.2,
        fillColor: fillColor,
        fillOpacity: 0.6,

        strokeStyle: 'solid',

        type: type,
      })

      // AMap.event.addListener(mouseTool, 'draw', function (e) {
      //     console.log(e.obj.getPath());//获取路径/范围
      // });
    },

    //停车点
    addParkingSpace() {
      // console.log("parking");
      const fillColor = '#aab86d'
      const type = 'parkingspace'
      this.drawPolygon(this.mouseTool, fillColor, type)
    },

    search() {
      console.log(this.input)
    },

    // showPath(){
    //   console.log(this.form);

    // },

    handleOpen(key, keyPath) {
      console.log(key, keyPath)
    },

    handleClose(key, keyPath) {
      console.log(key, keyPath)
    },

    //热力图
    showHeatMap() {
      setTimeout(() => {
        this.heatMap.show()
      }, 1000)
      this.initHeatMapBox()

      const mapBox = document.getElementById('container1')
      mapBox.style.width = '700px'
      mapBox.style.height = '600px'
      mapBox.style.position = 'relative'
      mapBox.style.float = 'left'
      mapBox.style.left = ' -246px'
      mapBox.style.top = '10px'
    },

    hideHeatMap() {
      this.heatMap.hide()

      const mapBox = document.getElementById('container1')
      mapBox.style.width = '1290px'
      // mapBox.style.height='700px'
      // mapBox.style.position='relative'
      mapBox.style.left = ' 0px'
      mapBox.style.top = '0px'
    },

    initmap() {
      AMapLoader.load({
        key: 'a97c01458bc53a763703fcd1dd647f59', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          'AMap.GeoJSON',
          'AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.HeatMap',
        ],
      }).then((AMap) => {
        this.map = new AMap.Map('container1', {
          resizeEnable: true,
          viewMode: '2D', // 默认使用 2D 模式
          zoom: 18, //初始化地图层级
          center: [113.355, 23.1575], //初始化地图中心点
        })

        //输入提示
        var auto = new AMap.Autocomplete({
          input: 'tipinput',
        })

        var auto = new AMap.AutoComplete(auto)
        var placeSearch = new AMap.PlaceSearch({
          map: this.map,
        }) //构造地点查询类
        auto.on('select', select) //注册监听，当选中某条记录时会触发
        function select(e) {
          placeSearch.setCity(e.poi.adcode)
          placeSearch.search(e.poi.name) //关键字查询查询
        }

        let geojson = new AMap.GeoJSON({
          geoJSON: null,
        })

        this.AMap = AMap
        this.geojson = geojson

        this.polyLineGeoJson = new AMap.GeoJSON({
          geoJSON: null,
        })
        this.polylineRecord = new Set()

        //获取所有共享单车
        this.getAllSharedBike(geojson)

        //获取所有共享电动车
        this.getAllSharedEbike(geojson)

        //获取停车点
        this.getParkingLots()

        //获取充电桩
        this.getChargingPiles(geojson)

        //获取所有维修点

        this.getRepairPoints()

        this.getSCAUPoi()

        this.map.plugin(
          [
            'AMap.ToolBar',
            'AMap.Scale',
            'AMap.HawkEye',
            'AMap.MapType',
            'AMap.Geolocation',
            'AMap.MouseTool',
            'AMap.MoveAnimation',
          ],
          () => {
            // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
            this.map.addControl(new AMap.ToolBar())

            // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
            // this.map.addControl(new AMap.Scale());

            // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
            this.map.addControl(new AMap.HawkEye({ isOpen: true }))

            // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
            this.map.addControl(new AMap.MapType())
          }
        )

        const mouseTool = new AMap.MouseTool(this.map)

        this.mouseTool = mouseTool

        //覆盖物绘制事件
        mouseTool.on('draw', (event) => {
          //判断矢量覆盖物类型
          if (event.obj.type == 'AMap.Marker') {
            this.lng = event.obj._opts.position.lng
            this.lat = event.obj._opts.position.lat

            //共享电动车
            if (event.obj._opts.type == 'ebike') {
              ;(this.form.no = ''),
                (this.form.state = ''),
                (this.form.color = ''),
                (this.form.battery = '')

              this.dialogVisible = true
              this.flag1 = true
              this.pType = 'ebike'
              this.rules = this.rules1
            } //共享单车
            else if (event.obj._opts.type == 'bike') {
              // console.log("addbike");

              ;(this.form.no = ''),
                (this.form.state = ''),
                (this.form.color = ''),
                (this.dialogVisible = true)
              this.flag1 = false
              this.pType = 'bike'
              this.rules = this.rules2
            } else if (event.obj._opts.type == 'repairPoint') {
              let rpId = nanoid()

              this.$axios({
                method: 'post',
                url: `/repairPoint/add?lng=${this.lng}&lat=${this.lat}&rpId=${rpId}`,
              }).then((res) => {})
            } else if (event.obj._opts.type == 'destination') {
              console.log('destination')

              fetch(
                `https://restapi.amap.com/v3/direction/walking?origin=${this.originLng},${this.originLat}&destination=${event.obj._opts.position.lng},${event.obj._opts.position.lat}&key=91077649ed5b33dbf88aaf005f3bdc3c`,
                {
                  method: 'get',
                }
              ).then(async (res) => {
                res = await res.json()

                let pathList = []
                let pathInfo = res.route.paths[0].steps

                for (let index = 0; index < pathInfo.length; index++) {
                  let p2 = pathInfo[index].polyline.split(';')
                  for (let index = 0; index < p2.length; index++) {
                    pathList.push(
                      new AMap.LngLat(
                        p2[index].split(',')[0],
                        p2[index].split(',')[1]
                      )
                    )
                  }
                }

                var polyline = new AMap.Polyline({
                  path: pathList,

                  borderWeight: 2, // 线条宽度，默认为 1
                  showDir: true,
                  strokeColor: 'red', //线颜色
                  strokeWeight: 6, //线宽
                  lineJoin: 'round', // 折线拐点连接处样式
                })

                // 将折线添加至地图实例
                this.map.add(polyline)
                this.showDestinationFalse()
                mouseTool.close()
              })
            }
          } else if (event.obj.type == 'AMap.Overlay') {
            //获取多边形顶点
            const arr = event.obj._opts.path
            let path = []
            if (arr) {
              for (let index = 0; index < arr.length; index++) {
                let pair = {
                  lng: arr[index][0],
                  lat: arr[index][1],
                }
                path.push(pair)
              }
            }
            let str2 = ''

            for (let index = 0; index < path.length; index++) {
              let str = path[index].lng + ' ' + path[index].lat + ';'
              str2 += str
            }
            //停车场
            if (event.obj._opts.type == 'parkingspace') {
              //添加停车场
              this.$axios({
                method: 'post',
                url: `/addStop?points=${str2}`,
                data: { str2, sid: nanoid() },
              }).then((res) => {
                console.log(res)
              })
            }
            //添加充电桩
            else if (event.obj._opts.type == 'chargingPile') {
              this.$axios({
                method: 'post',
                url: `/addChargingPile?points=${str2}`,
                data: { str2, cpId: nanoid() },
              }).then((res) => {
                console.log(res)
              })
            }
          }
        })

        //解除绘制
        this.map.on('rightclick', () => {
          mouseTool.close()
          window.location.reload()
        })
      })
    },

    initHeatMapBox() {
      AMapLoader.load({
        key: 'a97c01458bc53a763703fcd1dd647f59',
        version: '2.0',
        plugins: [
          'AMap.GeoJSON',
          'AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.HeatMap',
        ],
      })
        .then((AMap) => {
          this.map = new AMap.Map('heatMapBox', {
            viewMode: '2D', //是否为3D地图模式
            zoom: 16, //初始化地图级别
            center: [113.355, 23.1575], //初始化地图中心点位置
          })

          //初始化heatmap对象
          this.heatMap = new AMap.HeatMap(this.map, {
            radius: 25, //给定半径
            opacity: [0, 0.8],
            /*,
                gradient:{
                    0.5: 'blue',
                    0.65: 'rgb(117,211,248)',
                    0.7: 'rgb(0, 255, 0)',
                    0.9: '#ffea00',
                    1.0: 'red'
                }
                 */
          })
          //设置数据集：该数据为北京部分“公园”数据
          this.heatMap.setDataSet({
            data: this.heatMapDataList,
            max: 100,
          })

          this.heatMap.hide()
        })
        .catch((e) => {
          console.log(e)
        })
    },

    select(e) {
      this.placeSearch.setCity(e.poi.adcode)
      this.placeSearch.search(e.poi.name) //关键字查询查询
    },

    generateRandomEBike() {
      var points = turf.randomPoint(100, {
        bbox: [113.360153, 23.163136, 113.344365, 23.156621],
      })

      var sample = turf.sample(points, 100)

      console.log(sample)

      for (let index = 0; index < sample.features.length; index++) {
        // console.log(sample.features[index].geometry.coordinates);
        //参数
        const params = {
          no: index,
          state: 'using',
          cumlative_usage_time: '53h',
          monthly_usage_times: '53',
          trial: '',
          color: 'NaN',
          battery: 'NaN',
          lng: sample.features[index].geometry.coordinates[0],
          lat: sample.features[index].geometry.coordinates[1],
        }

        //添加共享电动车
        this.$axios({
          method: 'post',
          url: `/addSharedEBike`,
          data: params,
        }).then((res) => {
          // console.log(res);
        })
      }
    },

    getSCAUPoi() {
      let geojson = new AMap.GeoJSON({
        geoJSON: null,
      })

      for (let index = 0; index < poiData.poiData.pois.length; index++) {
        let info = poiData.poiData.pois[index]
        let marker = new AMap.Marker({
          position: new AMap.LngLat(
            info.location.split(',')[0],
            info.location.split(',')[1]
          ),
          address: info.address,
          name: info.name,
          tel: info.tel,
          type: info.type,
          photos: info.photos,
        })

        this.map.add(marker)
        geojson.addOverlay(marker)
      }

      geojson.eachOverlay((item) => {
        item.on('click', (e) => {
          console.log(e.target._opts.photos)
          if (e.target._opts.photos.length === 0) {
            this.photosFlag = false
          } else {
            this.photosFlag = true
          }
          this.poiInfoForm.name = e.target._opts.name
          this.poiInfoForm.address = e.target._opts.address
          this.poiInfoForm.tel = e.target._opts.tel
          this.poiInfoForm.type = e.target._opts.type
          this.poiInfoForm.photos = e.target._opts.photos
          this.edittrue3()
        })
      })
    },
  },
}
</script>

<style>
.el-header,
.el-footer {
  background-color: #687581;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #687581;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-main {
  /* background-color: #9bbbdb; */
  color: #333;
  text-align: center;
  line-height: 160px;
  height: 700px;
  overflow: hidden;
}

#container1 {
  width: 1290px;

  /* width: 700px; */
  /* position: relative; */
  /* left: -246px; */
  /* top:10px; */

  height: 610px;
  z-index: 99;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.header1 {
  border-radius: 5px;
}
</style>
